package ssi.actions;

import java.sql.Connection;
import java.sql.Date;
import java.sql.Statement;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import ssi.beans.Message;
import ssi.beans.User;
import ssi.tools.Connector;

public class SendMessageAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		String target = null;
		ActionErrors actionErrors = new ActionErrors();
		Message message=(Message)form;
		User user = (User)session.getAttribute("user");
		int senderId=user.getId();
		int receiverId=message.getReceiverId();
		String title=message.getTitle();
		String text=message.getText();
		Calendar calendar = Calendar.getInstance();
		Date data = new Date(calendar.getTime().getTime());
		String sentDate = data.toString();
		System.err.println("DANE: " + senderId + receiverId + title + text + sentDate);
		if(!((title==null || title.equals("")) && ((text==null) || text.equals("")))){
			try{
			Connection connection = new Connector().getConnection();
			Statement statement = connection.createStatement();
			statement.executeUpdate("INSERT INTO `messages`(`title`, `text`, `sent_date` ,`receiver_id`, `sender_id` ) VALUES(\""+title+"\", \""+text+"\", \""+sentDate+"\", "+receiverId+", "+senderId+")");
			target="success";
			actionErrors.add("error",
					new ActionMessage("error.messageSent"));
			connection.close();
			}catch(Exception e){
				//catch blad
				actionErrors.add("error",
						new ActionMessage("error.catch"));
			}
		}else{
			//puste pola
			actionErrors.add("error",
					new ActionMessage("error.emptyFields"));
		}
		
		if(actionErrors.size() !=0){
			extracted(request, actionErrors);
			return new ActionForward(mapping.getInput());
		}
		
		
		return mapping.findForward(target);
	}
	private void extracted(HttpServletRequest request, ActionErrors actionErrors) {
		saveErrors(request, actionErrors);
	}
}
